import json
from typing import List, Dict, Any
from models.word import Word
from database.db_manager import DBManager

class JSONImporter:
    """JSON词库导入工具"""
    
    def __init__(self, db_manager: DBManager):
        self.db_manager = db_manager
        
    def import_from_file(self, file_path: str):
        """从JSON文件导入单词"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                
            if not isinstance(data, list):
                return 0, "JSON格式错误：根元素必须是数组"
                
            words = []
            for item in data:
                if not isinstance(item, dict):
                    continue
                    
                word = Word(
                    word=item.get('word', ''),
                    phonetic=item.get('phonetic', ''),
                    meaning=item.get('meaning', ''),
                    example=item.get('example', ''),
                    category=item.get('category', '')
                )
                
                if word.word and word.meaning:  # 确保单词和释义不为空
                    words.append(word)
                    
            if not words:
                return 0, "未找到有效的单词数据"
                
            count = self.db_manager.bulk_add_words(words)
            return count, f"成功导入 {count} 个单词（重复单词已跳过）"
            
        except FileNotFoundError:
            return 0, f"文件未找到：{file_path}"
        except json.JSONDecodeError:
            return 0, "JSON解析错误：文件格式不正确"
        except Exception as e:
            return 0, f"导入失败：{str(e)}"